package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import objects.Movie;

public class MoviesQueries {

	private static final String DATABASE_URL = "jdbc:mysql://localhost/MovieBase";
	private static final String USERNAME = "moviebase";
	private static final String PASSWORD = "moviebase";

	private Connection connection = null;
	private PreparedStatement selectAllMovie = null;
	private PreparedStatement insertNewMovie = null;
	private PreparedStatement checkoutMovie = null;

	public MoviesQueries() {
		try {
			connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
					PASSWORD);

			selectAllMovie = connection
					.prepareStatement("SELECT * FROM Movie");

			insertNewMovie = connection
					.prepareStatement("INSERT INTO Movie (moid, title, year, location, `out`) VALUES "
							+ "(?,?,?,?,?)");
			
			checkoutMovie = connection
					.prepareStatement("UPDATE `MovieBase`.`Movie` SET `out`=? WHERE `moid`=?");

		} catch (SQLException e) {
			System.out.println(e);
		}
	}

	public List<Movie> getAllMovies() {
		List<Movie> results = null;
		ResultSet resultSet = null;

		try {
			resultSet = selectAllMovie.executeQuery();
			results = new ArrayList<Movie>();

			while (resultSet.next()) {
				results.add(new Movie(resultSet.getInt("moid"), resultSet
						.getString("title"), resultSet.getInt("year"),
						resultSet.getInt("location"), resultSet.getInt("out")));
			}
		} catch (SQLException e) {
			System.out.println(e);
		} finally {
			try {
				resultSet.close();
			} catch (SQLException e) {

			}
		}
		return results;
	}

	public int addMovie(int moid, String title, int year, int loc, int out) {
		int result = 0;

		try {
			insertNewMovie.setInt(1, moid);
			insertNewMovie.setString(2, title);
			insertNewMovie.setInt(3, year);
			insertNewMovie.setInt(4, loc);
			insertNewMovie.setInt(5, out);

			result = insertNewMovie.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e);
			close();
		}

		return result;
	}

	public void close() {
		try {
			connection.close();
		} catch (SQLException e) {
			System.out.println(e);
		}
	}
	
	public int checkoutMovie(int moid, int out) {
		int result = 0;

		try {
			checkoutMovie.setInt(1, out);
			checkoutMovie.setInt(2, moid);

			result = checkoutMovie.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e);
			close();
		}

		return result;
	}
}
